<?php

namespace App\Http\Models;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Item extends Model
{
    public static function give($uid, $reward, &$uinfo, $from='') {
        if(empty($reward) || !is_array($reward)) return false;

        $add_fodder = 0;
        $add_rewards = [];
        $add_batchs  = [];
        $batchs = [];
        foreach($reward as $r) {
            if(!isset($r['type'])) continue;
            if($r['type'] != config('game.cfg.ItemTypeCoupon') && !isset($r['num'])) continue;
            switch($r['type']) {
                case config('game.cfg.ItemTypeFodder'):

                    // 判断饲料池是否超了
                    $old_fodder = $uinfo['fodder'];
                    // $max_fodder = min(config('game.cfg.BasePerProductStarFeedCount')+$uinfo['level']*200, config('game.cfg.BaseMaxStorageFodderNum'));
                    $max_fodder = config('game.cfg.BaseMaxStorageFodderNum');
                    $uinfo['fodder'] += $r['num'];
                    // 新增规则, 签到可以超出上限
                    if($uinfo['fodder'] > $max_fodder && !strstr($from, 'sign_day')) {
                        $uinfo['fodder'] = $max_fodder;
                        $real_add = $uinfo['fodder'] - $old_fodder;
                    } else {
                        $uinfo['fodder'] += $r['num'];
                        $real_add = $r['num'];
                    }

                    // 排行榜奖励特殊处理
                    $r['name'] = '饲料';
                    if($from == 'gain_star_level') {
                        $add_rewards[] = $r;
                    } else {
                        $r['num'] = $real_add;
                        $add_rewards[] = $r;
                    }
                    if($real_add > 0) {
                        DB::table('users')->where('id', $uid)->increment('fodder', $real_add);
                        $add_fodder = $real_add;

                        file_put_contents('/tmp/fodder_change.log', date('Y-m-d').' ===== '.'  uid:'.$uid.' from:'.$from
                            .'  change:'.$real_add.'  before:'.$uinfo['fodder'].'  after:'.($uinfo['fodder']+$real_add)."\n", FILE_APPEND);
                    }

                    #file_put_contents('/tmp/fodder.log', date('Y-m-d H:i:s')."=========================\n".$uid."\n".json_encode($reward)."\n\n", FILE_APPEND);

                    break;
                case config('game.cfg.ItemTypeCoupon'):
                    file_put_contents('/tmp/exchange_coupon_from_item.log', date('Y-m-d H:i:s') . "==================================\n" . $r['extra']."\n", FILE_APPEND);
                    $extra_arr = explode(',', $r['extra']);
                    $seed = array_rand($extra_arr, 1);
                    $batch_num = $extra_arr[$seed];
                    file_put_contents('/tmp/exchange_coupon_from_item.log', $batch_num."\n", FILE_APPEND);

                    $get_coupons = DB::table('game_sign_coupon')->where('batch_number', $batch_num)->first();
                    if(isset($get_coupons['id'])) {
                        $add_batchs[] = [
                            'name' => $get_coupons['coupon_name'],
                            'img' => $get_coupons['coupon_url'],
                            'batch' => $get_coupons['batch_number'],
                            'num' => 1,
                        ];
                        file_put_contents('/tmp/exchange_coupon_from_item.log', json_encode($get_coupons)."\n", FILE_APPEND);

                        // 兑换券
                        $uri = '/activity-endorsement/endorsement/coupon-activity/v1/coupon';
                        // $pstr = 'batchId=' . $batch_num . '&clientId=' . config('game.cfg.appid') . '&lyfuid=' . $uinfo['openid'];
                        // $url = config('game.cfg.origin_api') . $uri . '?' . $pstr;
                        $pstr = 'batchId=' . $batch_num . '&clientId=' . env('APPID') . '&lyfuid=' . $uinfo['openid'];
                        $url = env('ORIGIN_API') . $uri . '?' . $pstr;

                        $sig_time = Controller::now();
                        $sig = base64_encode(hash_hmac(
                            "sha1",
                            "GET\n" .
                            $uri . "\n" .
                            $pstr . "\n" .
                            // "x-co-client:" . config('game.cfg.appid') . "\n" .
                            "x-co-client:" . env('APPID') . "\n" .
                            "x-co-timestamp:" . $sig_time,
                            // config('game.cfg.appsecret'),
                            env('APPSECRET'),
                            true
                        ));
                        $headers = [
                            'Content-Type:application/json',
                            // 'X-Co-Client:' . config('game.cfg.appid'),
                            'X-Co-Client:' . env('APPID'),
                            'X-Co-TimeStamp:' . $sig_time,
                            'X-Co-Sign:' . $sig,
                        ];

                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, $url);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                        $output = curl_exec($ch);
                        curl_close($ch);
                        $exchange_result = json_decode($output, true);
                        file_put_contents('/tmp/exchange_coupon_from_item.log', date('Y-m-d H:i:s') . "==================================\n" . $batch_num . ' - ' . $output . "\n\n", FILE_APPEND);
                    }
                    break;
                case config('game.cfg.ItemTypePostcard'):
                    break;
                case config('game.cfg.ItemTypeSpecialty'):
                    break;
                case config('game.cfg.ItemTypeFragment'):
                    $itemConf = config('item.cfg');
                    if(isset($itemConf[$r['id']])) {
                        $dressConf = config('dressup.cfg');
                        if(isset($dressConf[$itemConf[$r['id']]['parent']])) {
                            $df = $dressConf[$itemConf[$r['id']]['parent']];
                            $tids = explode(',', $df['tid']);
                            // 检查任务是否全完成
                            $tasks = DB::table('user_task')->where('uid', $uid)->whereIn('tid', $tids)->get();
                            if (count($tasks) >= count($tids)) {
                                $has = true;
                                foreach ($tasks as $task) {
                                    if ($task['status'] != config('game.cfg.TaskStatusReceived')) {
                                        $has = false;
                                        break;
                                    }
                                }
                                if ($has === true) {
                                    $duration = ($dressConf[$itemConf[$r['id']]['parent']]['duration'] * 86400);
                                    $now = time();
                                    // DB::statement("REPLACE INTO dressups(userId, confId, lastGetTime, durationTime) values ('".$uid."', '".$itemConf[$r['id']]['parent']."', '".time()."', '".$duration."')");
                                    $data = DB::table('dressups')->where(['userId'=>$uid, 'confId'=>$itemConf[$r['id']]['parent']])->first();
                                    if(empty($data) || count($data) <= 0) {
                                        DB::table('dressups')->insert([
                                            'userId' => $uid,
                                            'confId' => $itemConf[$r['id']]['parent'],
                                            'lastGetTime'=>$now,
                                            'durationTime' => $duration
                                        ]);
                                    } else {
                                        if( $now >= ($data['lastGetTime'] + $data['durationTime'])) {
                                            DB::table('dressups')->where(['userId'=>$uid, 'confId'=>$itemConf[$r['id']]['parent']])->update([
                                                'lastGetTime'=>$now,
                                                'durationTime' => $duration
                                            ]);
                                        } else {
                                            DB::table('dressups')->where(['userId'=>$uid, 'confId'=>$itemConf[$r['id']]['parent']])->increment('durationTime', $duration);
                                        }
                                    }
                                    $add_rewards[] = $r;
                                }
                            }
                        }
                    }
                    break;
                case config('game.cfg.ItemTypeStar'):
                    if(!$uinfo) return false;
                    // 增加星星升级
                    if(isset($uinfo['id'])) {
                        // $old_level = $uinfo['level'];
                        $uinfo['star'] += $r['num'];
                        $uinfo['totalStar'] += $r['num'];
                        // $uinfo['level'] = intval(($uinfo['totalStar']+11) / config('game.cfg.BasePerLvupStarNum'));
                        // $uinfo['exp'] = ($uinfo['totalStar']+11) % config('game.cfg.BasePerLvupStarNum');
                        DB::table('users')->where('id', $uid)->update([
                            'star' => $uinfo['star'],
                            'totalStar' => $uinfo['totalStar'],
                            // 'level' => $uinfo['level'],
                            // 'exp' => $uinfo['exp'],
                        ]);
                        // if($uinfo['level'] > $old_level) {
                        //     Task::setProgress($uid, 0, $uinfo['level']);
                        // }
                        $add_rewards[] = $r;
                    }
                    break;
                case 555:
                    // $itemConf = config('item.cfg');
                    $now = time();
                    $data = DB::table('dressups')->where(['userId'=>$uid, 'confId'=>$r['id']])->first();
                    // var_dump($data);exit;
                    if(empty($data) || count($data) <= 0) {
                        DB::table('dressups')->insert([
                            'userId' => $uid,
                            'confId' => $r['id'],
                            'lastGetTime'=>$now,
                            'durationTime' => $r['duration']
                        ]);
                    } else {
                        if( $now >= ($data['lastGetTime'] + $data['durationTime'])) {
                            DB::table('dressups')->where(['userId'=>$uid, 'confId'=>$r['id']])->update([
                                'lastGetTime'=>$now,
                                'durationTime' => $r['duration']
                            ]);
                        } else {
                            DB::table('dressups')->where(['userId'=>$uid, 'confId'=>$r['id']])->increment('durationTime', $r['duration']);
                        }
                    }
                    $add_rewards[] = $r;
                    break;
            }
        }

        return [
            'rewards' => $add_rewards,
            'batchs'  => $add_batchs,
            'fodder'  => $add_fodder,
        ];
    }
}
